// ============================================================================
// 通知容器组件
// ============================================================================

import React, { useEffect, useRef, useState } from 'react'
import {
  CheckCircleIcon,
  ExclamationTriangleIcon,
  InformationCircleIcon,
  XCircleIcon,
  XMarkIcon
} from '@heroicons/react/24/outline'

/**
 * 通知数据接口
 */
interface NotificationData {
  id: string
  type: 'info' | 'success' | 'warning' | 'error'
  title: string
  message: string
  duration?: number
  actions?: Array<{
    label: string
    action: () => void
  }>
}

/**
 * 通知图标映射
 */
const notificationIcons = {
  success: CheckCircleIcon,
  error: XCircleIcon,
  warning: ExclamationTriangleIcon,
  info: InformationCircleIcon
}

/**
 * 通知样式映射
 */
const notificationStyles = {
  success: 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800 text-green-800 dark:text-green-200',
  error: 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800 text-red-800 dark:text-red-200',
  warning: 'bg-yellow-50 dark:bg-yellow-900/20 border-yellow-200 dark:border-yellow-800 text-yellow-800 dark:text-yellow-200',
  info: 'bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800 text-blue-800 dark:text-blue-200'
}

/**
 * 单个通知组件
 */
function NotificationItem({ 
  notification, 
  onClose 
}: { 
  notification: NotificationData
  onClose: (id: string) => void 
}) {
  const Icon = notificationIcons[notification.type]
  const styles = notificationStyles[notification.type]

  return (
    <div
      className={`relative p-4 border rounded-lg shadow-lg transition-all duration-300 transform ${styles}`}
    >
      <div className="flex items-start space-x-3">
        <Icon className="w-5 h-5 flex-shrink-0 mt-0.5" />
        
        <div className="flex-1 min-w-0">
          <h4 className="font-medium text-sm">
            {notification.title}
          </h4>
          <p className="text-sm opacity-90 mt-1">
            {notification.message}
          </p>
          
          {notification.actions && notification.actions.length > 0 && (
            <div className="flex space-x-2 mt-3">
              {notification.actions.map((action, index) => (
                <button
                  key={index}
                  onClick={action.action}
                  className="text-xs font-medium underline hover:no-underline"
                >
                  {action.label}
                </button>
              ))}
            </div>
          )}
        </div>
        
        <button
          onClick={() => onClose(notification.id)}
          className="flex-shrink-0 p-1 rounded-md hover:bg-black/10 dark:hover:bg-white/10 transition-colors"
        >
          <XMarkIcon className="w-4 h-4" />
        </button>
      </div>
    </div>
  )
}

/**
 * 通知容器组件
 */
export function NotificationContainer() {
  const [notifications, setNotifications] = useState<NotificationData[]>([])
  const timeoutsRef = useRef<Map<string, NodeJS.Timeout>>(new Map())

  // 监听通知事件
  useEffect(() => {
    const handleShowNotification = (event: CustomEvent) => {
      const notification = event.detail as NotificationData
      setNotifications(prev => [...prev, notification])

      // 设置自动关闭定时器
      if (notification.duration && notification.duration > 0) {
        const timeout = setTimeout(() => {
          handleHideNotification(notification.id)
        }, notification.duration)
        timeoutsRef.current.set(notification.id, timeout)
      }
    }

    const handleHideNotification = (id: string) => {
      setNotifications(prev => prev.filter(n => n.id !== id))
      const timeout = timeoutsRef.current.get(id)
      if (timeout) {
        clearTimeout(timeout)
        timeoutsRef.current.delete(id)
      }
    }

    const handleHideNotificationEvent = (event: CustomEvent) => {
      handleHideNotification(event.detail.id)
    }

    const handleClearAll = () => {
      setNotifications([])
      timeoutsRef.current.forEach(timeout => clearTimeout(timeout))
      timeoutsRef.current.clear()
    }

    window.addEventListener('show-notification', handleShowNotification as EventListener)
    window.addEventListener('hide-notification', handleHideNotificationEvent as EventListener)
    window.addEventListener('clear-all-notifications', handleClearAll)

    return () => {
      window.removeEventListener('show-notification', handleShowNotification as EventListener)
      window.removeEventListener('hide-notification', handleHideNotificationEvent as EventListener)
      window.removeEventListener('clear-all-notifications', handleClearAll)
      timeoutsRef.current.forEach(timeout => clearTimeout(timeout))
      timeoutsRef.current.clear()
    }
  }, [])

  const closeNotification = (id: string) => {
    setNotifications(prev => prev.filter(n => n.id !== id))
    const timeout = timeoutsRef.current.get(id)
    if (timeout) {
      clearTimeout(timeout)
      timeoutsRef.current.delete(id)
    }
  }

  if (notifications.length === 0) {
    return null
  }

  return (
    <div className="fixed top-4 right-4 z-50 space-y-3 max-w-sm w-full">
      {notifications.map((notification) => (
        <NotificationItem
          key={notification.id}
          notification={notification}
          onClose={closeNotification}
        />
      ))}
    </div>
  )
}
